"""
文档分享 API
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.models.document import Document
from app.models.document_share import DocumentShare, SharePermission
from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/shares", tags=["shares"])


class ShareCreate(BaseModel):
    """分享创建请求"""
    document_id: str
    shared_to_id: str
    permission: str = "view"  # view, download, comment
    expires_at: Optional[str] = None  # ISO格式时间字符串


class ShareResponse(BaseModel):
    """分享响应"""
    id: str
    document_id: str
    document_title: str
    shared_by_id: str
    shared_by_name: str
    shared_to_id: str
    shared_to_name: str
    permission: str
    expires_at: Optional[datetime]
    created_at: datetime
    
    class Config:
        from_attributes = True


@router.post("/", response_model=ShareResponse)
async def create_share(
    share_data: ShareCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建文档分享
    
    Args:
        share_data: 分享数据
        current_user: 当前用户
        db: 数据库会话
    
    Returns:
        分享记录
    """
    # 查询文档
    document = db.query(Document).filter(Document.id == share_data.document_id).first()
    if not document:
        raise HTTPException(status_code=404, detail="文档不存在")
    
    # 权限检查：只有文档所有者才能分享
    if document.upload_user_id != str(current_user.id):
        raise HTTPException(status_code=403, detail="只有文档所有者才能分享文档")
    
    # 检查目标用户是否存在
    target_user = db.query(User).filter(User.id == share_data.shared_to_id).first()
    if not target_user:
        raise HTTPException(status_code=404, detail="目标用户不存在")
    
    # 不能分享给自己
    if str(current_user.id) == share_data.shared_to_id:
        raise HTTPException(status_code=400, detail="不能分享给自己")
    
    # 检查是否已经分享给该用户
    existing_share = db.query(DocumentShare).filter(
        and_(
            DocumentShare.document_id == share_data.document_id,
            DocumentShare.shared_to_id == share_data.shared_to_id
        )
    ).first()
    
    if existing_share:
        # 更新现有分享
        existing_share.permission = SharePermission(share_data.permission)
        if share_data.expires_at:
            existing_share.expires_at = datetime.fromisoformat(share_data.expires_at.replace('Z', '+00:00'))
        existing_share.updated_at = datetime.utcnow()
        db.commit()
        db.refresh(existing_share)
        
        share = existing_share
    else:
        # 创建新分享
        share = DocumentShare(
            document_id=share_data.document_id,
            shared_by_id=str(current_user.id),
            shared_to_id=share_data.shared_to_id,
            permission=SharePermission(share_data.permission),
            expires_at=datetime.fromisoformat(share_data.expires_at.replace('Z', '+00:00')) if share_data.expires_at else None
        )
        db.add(share)
        db.commit()
        db.refresh(share)
    
    logger.info(f"用户 {current_user.username} 分享文档 {document.title} 给用户 {target_user.username}")
    
    return ShareResponse(
        id=share.id,
        document_id=share.document_id,
        document_title=document.title,
        shared_by_id=share.shared_by_id,
        shared_by_name=current_user.username,
        shared_to_id=share.shared_to_id,
        shared_to_name=target_user.username,
        permission=share.permission.value,
        expires_at=share.expires_at,
        created_at=share.created_at
    )


@router.get("/received", response_model=List[ShareResponse])
async def get_received_shares(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取分享给当前用户的所有文档
    
    Args:
        current_user: 当前用户
        db: 数据库会话
    
    Returns:
        分享列表
    """
    shares = db.query(DocumentShare).filter(
        DocumentShare.shared_to_id == str(current_user.id)
    ).all()
    
    result = []
    for share in shares:
        # 检查是否过期
        if share.expires_at and share.expires_at < datetime.utcnow():
            continue
        
        # 获取文档信息
        document = db.query(Document).filter(Document.id == share.document_id).first()
        if not document:
            continue
        
        # 获取分享者信息
        shared_by = db.query(User).filter(User.id == share.shared_by_id).first()
        
        result.append(ShareResponse(
            id=share.id,
            document_id=share.document_id,
            document_title=document.title,
            shared_by_id=share.shared_by_id,
            shared_by_name=shared_by.username if shared_by else "未知用户",
            shared_to_id=share.shared_to_id,
            shared_to_name=current_user.username,
            permission=share.permission.value,
            expires_at=share.expires_at,
            created_at=share.created_at
        ))
    
    return result


@router.get("/by-document/{document_id}", response_model=List[ShareResponse])
async def get_document_shares(
    document_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取某个文档的所有分享记录
    
    Args:
        document_id: 文档ID
        current_user: 当前用户
        db: 数据库会话
    
    Returns:
        分享列表
    """
    # 查询文档
    document = db.query(Document).filter(Document.id == document_id).first()
    if not document:
        raise HTTPException(status_code=404, detail="文档不存在")
    
    # 权限检查：只有文档所有者才能查看分享列表
    if document.upload_user_id != str(current_user.id):
        raise HTTPException(status_code=403, detail="只有文档所有者才能查看分享列表")
    
    shares = db.query(DocumentShare).filter(
        DocumentShare.document_id == document_id
    ).all()
    
    result = []
    for share in shares:
        # 获取被分享者信息
        shared_to = db.query(User).filter(User.id == share.shared_to_id).first()
        
        result.append(ShareResponse(
            id=share.id,
            document_id=share.document_id,
            document_title=document.title,
            shared_by_id=share.shared_by_id,
            shared_by_name=current_user.username,
            shared_to_id=share.shared_to_id,
            shared_to_name=shared_to.username if shared_to else "未知用户",
            permission=share.permission.value,
            expires_at=share.expires_at,
            created_at=share.created_at
        ))
    
    return result


@router.delete("/{share_id}")
async def delete_share(
    share_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    取消分享
    
    Args:
        share_id: 分享ID
        current_user: 当前用户
        db: 数据库会话
    
    Returns:
        成功消息
    """
    share = db.query(DocumentShare).filter(DocumentShare.id == share_id).first()
    if not share:
        raise HTTPException(status_code=404, detail="分享记录不存在")
    
    # 权限检查：只有分享者才能取消分享
    if share.shared_by_id != str(current_user.id):
        raise HTTPException(status_code=403, detail="只有分享者才能取消分享")
    
    document = db.query(Document).filter(Document.id == share.document_id).first()
    shared_to = db.query(User).filter(User.id == share.shared_to_id).first()
    
    db.delete(share)
    db.commit()
    
    logger.info(
        f"用户 {current_user.username} 取消了对用户 {shared_to.username if shared_to else '未知'} "
        f"的文档 {document.title if document else '未知'} 分享"
    )
    
    return {"message": "分享已取消"}

